#include "sendfile.h"

#include <QFile>
#include <QFileInfo>
#include <QTcpSocket>
#include <QThread>

SendFile::SendFile(QObject *parent)
    : QObject{parent}
{
    if (!tcp) {
        tcp = new QTcpSocket(this);
    }
    connect(tcp, &QTcpSocket::connected, this, &SendFile::connectOK);

    connect(tcp, &QTcpSocket::disconnected, [=]() {
        //        if(tcp)
        //        {
        //            tcp->close();
        //            tcp->deleteLater();
        //            tcp = nullptr;
        //            emit gameover();
        //        }
        emit gameover();
        });

    connect(tcp, &QTcpSocket::readyRead, [=]() {
        qDebug()<<"3current ThreadID"<<QThread::currentThread();
        //获取对方发送的内容
        QByteArray array = tcp->readAll();
        //追加到编辑区中
        emit recvMessage(QString::fromUtf8(array));
        });
    qDebug()<<"1current ThreadID"<<QThread::currentThread();
}

void SendFile::send(QString path)
{
    QFile file(path);
    QFileInfo info(path);

    file.open(QFile::ReadOnly);
    int fileSize=info.size();
    int num = 0;
    while(!file.atEnd())
    {
        if(num==0)
        {
            tcp->write((char*)&fileSize,4);
            num = 4;
        }
        QByteArray line = file.readLine();
        num += line.size();
        int percent = (num*100/fileSize);
        qDebug()<<percent;
        tcp->write(line);
        emit currentValue(percent);
    }
}

void SendFile::connectServer(unsigned short port, QString ip)
{
    if (!tcp) {
        tcp = new QTcpSocket(this);
    }
    tcp->connectToHost(QHostAddress(ip),port);
}

void SendFile::sendMessageSlot(QString message)
{
    tcp->write(message.toUtf8().data());
    tcp->flush(); // 确保数据立即发送
    qDebug()<<"2current ThreadID"<<QThread::currentThread();
}

void SendFile::disConnectServer()
{
    if (tcp) {
        tcp->disconnectFromHost();
        tcp->close();
    }
}
